package com.lance.answer.gui.answer.gk.answer.task;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.lance.answer.dto.CompleteInfo;
import com.lance.answer.gui.answer.AnswerObject;
import com.lance.answer.gui.answer.DealJsonString;
import com.lance.answer.gui.answer.Util;
import com.lance.answer.gui.answer.gk.answer.AnswerDTO;
import com.lance.answer.section_import.SectionImport;
import com.lance.answer.util.CollectionsUtil;
import com.lance.answer.util.HttpClientUtil;
import com.lance.answer.util.MD5Utils;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.openqa.selenium.By;
import org.openqa.selenium.Cookie;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.springframework.util.CollectionUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.time.Duration;
import java.util.*;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.TimeUnit;

@Slf4j
public class DoAnswerTaskTMP2022 extends Thread {


    private final String driverPath;
    private final LinkedBlockingDeque<AnswerDTO> answerDTOS;

    public DoAnswerTaskTMP2022(String driverPath, LinkedBlockingDeque<AnswerDTO> answerDTOS) {
        this.driverPath = driverPath;
        this.answerDTOS = answerDTOS;
    }

    @SneakyThrows
    @Override
    public void run() {

        while (answerDTOS.size() > 0) {
            AnswerDTO answerDTO = answerDTOS.take();
            String userName = answerDTO.getUsername();
            String password = answerDTO.getPwd();
            log.info("任务：{} 剩余 {} 行 用户名：{} 密码：{}",
                    Thread.currentThread().getName(), answerDTOS.size(), userName, password);
            run(driverPath, answerDTO);
            //todo
        }

        if (answerDTOS.size() == 0) {
            log.info("课程所有用户均已执行完毕，系统将在20min后结束");
            TimeUnit.MINUTES.sleep(20);
            return;
        }
    }


    // 管理学基础 2065001457555 19940419
    public static void run(String driverPath, AnswerDTO answerDTO) throws Exception {

//        Map<String, Double> urlMap = Maps.newLinkedHashMap();
//        for (AnswerRequestDTO requestDTO : answerDTO.getAnswerUrl()) {
//            urlMap.put(requestDTO.getUrl(), requestDTO.getScore());
//        }
        List<String> urlTasks = Lists.newArrayList();
        urlTasks.addAll(answerDTO.getAnswerUrl());

        Map<String, AnswerObject> answers = answerDTO.getAnswers();
        Map<String, AnswerObject> originAnswers = answerDTO.getOriginAnswers();
        String subjectName = answerDTO.getSubjectName();
        String userName = answerDTO.getUsername();
        String password = answerDTO.getPwd();
        boolean commit = answerDTO.isCommit();
        boolean push = answerDTO.isPush();


        //  String filePath = "E:\\answerInfo\\" + subjectName;
        String filePath = "libs//answerInfo//" + subjectName;
        //  String filePath = "D:\\project\\answer-tool\\libs\\answerInfo\\" + subjectName;

        if (!new File(filePath).exists()) {
            new File(filePath).mkdirs();
        }

        filePath = filePath + "//" + userName + ".txt";

        File completeInfoFile = new File(filePath);
        if (!completeInfoFile.exists()) {
            completeInfoFile.createNewFile();
        }
        InputStream inputStream = new FileInputStream(completeInfoFile);
        String completeInfoStr = IOUtils.toString(inputStream, "UTF-8");
        List<CompleteInfo> completeInfoList;
        try {
            completeInfoList = JSONObject.parseArray(completeInfoStr, CompleteInfo.class);
            if (null == completeInfoList) {
                completeInfoList = Lists.newArrayList();
            }
        } catch (Exception e) {
            completeInfoList = Lists.newArrayList();
        }
        Set<String> haveCompleteHomeWorkUrlSet = Sets.newHashSet();
        for (CompleteInfo info : completeInfoList) {
            if (info.isComplete()) {
                haveCompleteHomeWorkUrlSet.add(info.getHomeworkUrl());
            }
        }

        // 定义是否开启浏览器没有这门课程
        boolean isStartChrome = true;
        if (haveCompleteHomeWorkUrlSet.size() == urlTasks.size()) {
            isStartChrome = false;
        }


        WebDriver driver = Util.getDriver(driverPath);
        String url = "http://passport.ouchn.cn/Account/Login?ReturnUrl=%2Fconnect%2Fauthorize%2Fcallback%3Fclient_id%3Dstudentspace%26redirect_uri%3Dhttp%253A%252F%252Fstudent.ouchn.cn%252F%2523%252Fsignin-oidc%2523%26response_type%3Did_token%2520token%26scope%3Dopenid%2520profile%2520ouchnuser%2520ouchnstudentspaceapi%2520offline_access%26state%3Dca1cb5d0270b49fdaea508b8a846c457%26nonce%3Dd257df51b0a141ac8ed35b1caf59ef4c";
        driver.get(url);
        Thread.sleep(3000);
        //Util.login(driver, "2065001457555", "19940419");
        Util.login(driver, userName, password);
        Util.switchToFirst(driver);
        Thread.sleep(3000);

        // 判断是否找到课程
        boolean isFindSubject = false;

        //chromeDriver.navigate().refresh();
        for (WebElement we : driver.findElements(By.className("media-body"))) {
            Util.switchToFirst(driver);
            // 找到管理学基础
            String mediaTitle = we.findElement(By.className("media-title")).getText();

        //    if (!mediaTitle.equals(subjectName)) {
            if (!mediaTitle.contains(subjectName)) {
                continue;
            }

            isFindSubject = true;
            try {
                //点击进入学习的按钮
                WebElement studyButton = we.findElement(By.cssSelector("button[class='btn bg-primary']"));
                studyButton.click();
                //Util.switchToLast(driver);
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                try {
                    driver.close();
                    driver.quit();
                } catch (Exception e2) {

                }
            }
        }
        if (!isFindSubject) {
            try {
                CompleteInfo info = new CompleteInfo();
                info.setSummary("没有这门课程！");
                completeInfoList.add(info);
                FileUtils.write(completeInfoFile, JSONObject.toJSONString(completeInfoList, SerializerFeature.PrettyFormat), "utf-8");
                driver.close();
                driver.quit();
                return;
            } catch (Exception e) {

            }
        }

        Util.switchToLast(driver);
        String viewUrl = driver.getCurrentUrl();
        System.err.println("viewUrl:" + viewUrl);

        String testUrl = viewUrl + "&test=1";
        driver.get(testUrl);

        Thread.sleep(5000);


        urlTasks.clear();
//        urlTasks.add("http://shandong.ouchn.cn/mod/quiz/view.php?id=579298");
//        urlTasks.add("http://shandong.ouchn.cn/mod/quiz/view.php?id=579299");
//        urlTasks.add("http://shandong.ouchn.cn/mod/quiz/view.php?id=579300");
//        urlTasks.add("http://shandong.ouchn.cn/mod/quiz/view.php?id=579301");
//        urlTasks.add("http://shandong.ouchn.cn/mod/quiz/view.php?id=579302");


        for (WebElement we : new WebDriverWait(driver, Duration.ofSeconds(20)).until((ExpectedCondition<List<WebElement>>)
                d -> d.findElements(By.tagName("a")))) {
            String href = we.getAttribute("href");
            if (Strings.isNullOrEmpty(href) || !href.contains("quiz")) {
                continue;
            }
            if ("进入形考".equals(we.getText())) {
                urlTasks.add(href);
            }
            if (we.getText().contains("次形考")) {
                urlTasks.add(href);
            }
            if (we.getText().contains("形成性考核")
                    || we.getText().contains("形成性测验")
                    || we.getText().contains("形成性测试")
                    || we.getText().contains("终结性考核")
                    || we.getText().contains("期末测试")
                    || we.getText().contains("形考任务")
                    || we.getText().contains("终结性考试")
            ) {
                urlTasks.add(href);
            }
        }
//民事诉讼法学
        // FIXME 如果为空，就回到课程首页，获取所有的链接，找到quiz链接
        if (urlTasks.size() < 1) {
            driver.get(viewUrl);
            Thread.sleep(5000);
            urlTasks.addAll(getQuizUrl(driver, viewUrl));

            System.err.println("urlTasks:" + JSON.toJSONString(urlTasks));
        }

        if ("公共政策概论".equals(subjectName)) {
            urlTasks.clear();
            if (driver.getCurrentUrl().contains("anhui")) {
                urlTasks.add("http://anhui.ouchn.cn/mod/quiz/view.php?id=581886");
                urlTasks.add("http://anhui.ouchn.cn/mod/quiz/view.php?id=581888");
            }
        }
        if ("证据学".equals(subjectName)) {
            urlTasks.add("http://fujian.ouchn.cn/mod/quiz/view.php?id=361251");
            urlTasks.add("http://fujian.ouchn.cn/mod/quiz/view.php?id=361252");
            urlTasks.add("http://fujian.ouchn.cn/mod/quiz/view.php?id=361253");
        }
        if ("建筑工程项目管理".equals(subjectName)) {
            urlTasks.add("http://wuhan.ouchn.cn/mod/quiz/view.php?id=444875");
            urlTasks.add("http://wuhan.ouchn.cn/mod/quiz/view.php?id=444876");
            urlTasks.add("http://wuhan.ouchn.cn/mod/quiz/view.php?id=444877");
            urlTasks.add("http://wuhan.ouchn.cn/mod/quiz/view.php?id=444878");
            urlTasks.add("http://wuhan.ouchn.cn/mod/quiz/view.php?id=444879");
            urlTasks.add("http://wuhan.ouchn.cn/mod/quiz/view.php?id=444880");
        }

        if ("民事诉讼法学".equals(subjectName)) {
            urlTasks.add("http://xinjiang.ouchn.cn/mod/quiz/view.php?id=514677");
            urlTasks.add("http://xinjiang.ouchn.cn/mod/quiz/view.php?id=514678");
            urlTasks.add("http://xinjiang.ouchn.cn/mod/quiz/view.php?id=514679");
            urlTasks.add("http://xinjiang.ouchn.cn/mod/quiz/view.php?id=514680");
            urlTasks.add("http://xinjiang.ouchn.cn/mod/quiz/view.php?id=514681");
        }
        if ("计算机应用基础".equals(subjectName)) {
            //
            if (driver.getCurrentUrl().contains("shandong")) {
                urlTasks.add("http://shandong.ouchn.cn/mod/quiz/view.php?id=474316");
                urlTasks.add("http://shandong.ouchn.cn/mod/quiz/view.php?id=474317");
                urlTasks.add("http://shandong.ouchn.cn/mod/quiz/view.php?id=474318");
            }
            if (driver.getCurrentUrl().contains("xinjiang")) {
                urlTasks.add("http://xinjiang.ouchn.cn/mod/quiz/view.php?id=422931");
                urlTasks.add("http://xinjiang.ouchn.cn/mod/quiz/view.php?id=422932");
                urlTasks.add("http://xinjiang.ouchn.cn/mod/quiz/view.php?id=422933");
            }
        }
        if ("计算机应用基础(本)".equals(subjectName)) {
            urlTasks.add("http://hebei.ouchn.cn/mod/quiz/view.php?id=454021");
            urlTasks.add("http://hebei.ouchn.cn/mod/quiz/view.php?id=454022");
            urlTasks.add("http://hebei.ouchn.cn/mod/quiz/view.php?id=454023");
        }
        System.err.println("subjectName:" + subjectName);
        if ("西方行政学说".equals(subjectName)) {
            urlTasks.clear();
            System.err.println("?????????????????+" + driver.getCurrentUrl());
            if (driver.getCurrentUrl().contains("hebei")) {
                urlTasks.add("http://hebei.ouchn.cn/mod/quiz/view.php?id=502079");
            }
            if (driver.getCurrentUrl().contains("xinjiang")) {
                urlTasks.add("http://xinjiang.ouchn.cn/mod/quiz/view.php?id=474440");
            }
            if (driver.getCurrentUrl().contains("shanxi3")) {
                urlTasks.add("http://shanxi3.ouchn.cn/mod/quiz/view.php?id=477916");
            }
            if (driver.getCurrentUrl().contains("anhui")) {
                urlTasks.add("http://anhui.ouchn.cn/mod/quiz/view.php?id=531427");
            }
        }
        if ("公共行政学".equals(subjectName)) {
            urlTasks.clear();
            if (driver.getCurrentUrl().contains("xinjiang")) {
                urlTasks.add("http://xinjiang.ouchn.cn/mod/quiz/view.php?id=514372");
            }
            if (driver.getCurrentUrl().contains("jiangxi")) {
                urlTasks.add("http://jiangxi.ouchn.cn/mod/quiz/view.php?id=566248");
            }
            if (driver.getCurrentUrl().contains("xinjiang")) {
                urlTasks.add("http://xinjiang.ouchn.cn/mod/quiz/view.php?id=514372");
            }
            if (driver.getCurrentUrl().contains("wuhan")) {
                urlTasks.add("http://wuhan.ouchn.cn/mod/quiz/view.php?id=539868");
            }
        }
        if ("形势与政策".equals(subjectName)) {
            urlTasks.clear();
            // http://guizhou.ouchn.cn/mod/quiz/view.php?id=532504
            if (driver.getCurrentUrl().contains("shenzhen")) {
                urlTasks.add("http://shenzhen.ouchn.cn/mod/quiz/view.php?id=527416");
                urlTasks.add("http://shenzhen.ouchn.cn/mod/quiz/view.php?id=527417");
                urlTasks.add("http://shenzhen.ouchn.cn/mod/quiz/view.php?id=527418");
                urlTasks.add("http://shenzhen.ouchn.cn/mod/quiz/view.php?id=527419");
                urlTasks.add("http://shenzhen.ouchn.cn/mod/quiz/view.php?id=527420");
            }
            if (driver.getCurrentUrl().contains("guizhou")) {
                urlTasks.add("http://guizhou.ouchn.cn/mod/quiz/view.php?id=532504");
                urlTasks.add("http://guizhou.ouchn.cn/mod/quiz/view.php?id=532505");
                urlTasks.add("http://guizhou.ouchn.cn/mod/quiz/view.php?id=532506");
                urlTasks.add("http://guizhou.ouchn.cn/mod/quiz/view.php?id=532507");
                urlTasks.add("http://guizhou.ouchn.cn/mod/quiz/view.php?id=532508");
            }
            if (driver.getCurrentUrl().contains("guangdong")) {
                urlTasks.add("http://guangdong.ouchn.cn/mod/quiz/view.php?id=557089");
                urlTasks.add("http://guangdong.ouchn.cn/mod/quiz/view.php?id=557090");
                urlTasks.add("http://guangdong.ouchn.cn/mod/quiz/view.php?id=557091");
                urlTasks.add("http://guangdong.ouchn.cn/mod/quiz/view.php?id=557092");
                urlTasks.add("http://guangdong.ouchn.cn/mod/quiz/view.php?id=557093");
            }
            if (driver.getCurrentUrl().contains("xian")) {
                urlTasks.add("http://xian.ouchn.cn/mod/quiz/view.php?id=531431");
                urlTasks.add("http://xian.ouchn.cn/mod/quiz/view.php?id=531432");
                urlTasks.add("http://xian.ouchn.cn/mod/quiz/view.php?id=531433");
                urlTasks.add("http://xian.ouchn.cn/mod/quiz/view.php?id=531434");
                urlTasks.add("http://xian.ouchn.cn/mod/quiz/view.php?id=531435");
            }

            if (driver.getCurrentUrl().contains("hebei")) {
                urlTasks.add("http://hebei.ouchn.cn/mod/quiz/view.php?id=549333");
                urlTasks.add("http://hebei.ouchn.cn/mod/quiz/view.php?id=549334");
                urlTasks.add("http://hebei.ouchn.cn/mod/quiz/view.php?id=549335");
                urlTasks.add("http://hebei.ouchn.cn/mod/quiz/view.php?id=549336");
                urlTasks.add("http://hebei.ouchn.cn/mod/quiz/view.php?id=548093");
                urlTasks.add("http://hebei.ouchn.cn/mod/quiz/view.php?id=548094");
                urlTasks.add("http://hebei.ouchn.cn/mod/quiz/view.php?id=548095");
                urlTasks.add("http://hebei.ouchn.cn/mod/quiz/view.php?id=548096");
                urlTasks.add("http://hebei.ouchn.cn/mod/quiz/view.php?id=548097");
            }
            if (driver.getCurrentUrl().contains("shandong")) {
                urlTasks.add("http://shandong.ouchn.cn/mod/quiz/view.php?id=579298");
                urlTasks.add("http://shandong.ouchn.cn/mod/quiz/view.php?id=579299");
                urlTasks.add("http://shandong.ouchn.cn/mod/quiz/view.php?id=579300");
                urlTasks.add("http://shandong.ouchn.cn/mod/quiz/view.php?id=579301");
                urlTasks.add("http://shandong.ouchn.cn/mod/quiz/view.php?id=579302");
            }
            if (driver.getCurrentUrl().contains("gansu")) {
                urlTasks.add("http://gansu.ouchn.cn/mod/quiz/view.php?id=542290");
                urlTasks.add("http://gansu.ouchn.cn/mod/quiz/view.php?id=542291");
                urlTasks.add("http://gansu.ouchn.cn/mod/quiz/view.php?id=542292");
                urlTasks.add("http://gansu.ouchn.cn/mod/quiz/view.php?id=542293");
                urlTasks.add("http://gansu.ouchn.cn/mod/quiz/view.php?id=542294");
            }
            if (driver.getCurrentUrl().contains("xinjiang")) {
                urlTasks.add("http://xinjiang.ouchn.cn/mod/quiz/view.php?id=516745");
                urlTasks.add("http://xinjiang.ouchn.cn/mod/quiz/view.php?id=516746");
                urlTasks.add("http://xinjiang.ouchn.cn/mod/quiz/view.php?id=516747");
                urlTasks.add("http://xinjiang.ouchn.cn/mod/quiz/view.php?id=516748");
                urlTasks.add("http://xinjiang.ouchn.cn/mod/quiz/view.php?id=516749");
            }
            if (driver.getCurrentUrl().contains("anhui")) {
                urlTasks.add("http://anhui.ouchn.cn/mod/quiz/view.php?id=582995");
                urlTasks.add("http://anhui.ouchn.cn/mod/quiz/view.php?id=582996");
                urlTasks.add("http://anhui.ouchn.cn/mod/quiz/view.php?id=582997");
                urlTasks.add("http://anhui.ouchn.cn/mod/quiz/view.php?id=582998");
                urlTasks.add("http://anhui.ouchn.cn/mod/quiz/view.php?id=582999");
            }
            if (driver.getCurrentUrl().contains("qingdao")) {
                urlTasks.add("http://qingdao.ouchn.cn/mod/quiz/view.php?id=543152");
                urlTasks.add("http://qingdao.ouchn.cn/mod/quiz/view.php?id=543153");
                urlTasks.add("http://qingdao.ouchn.cn/mod/quiz/view.php?id=543154");
                urlTasks.add("http://qingdao.ouchn.cn/mod/quiz/view.php?id=543155");
                urlTasks.add("http://qingdao.ouchn.cn/mod/quiz/view.php?id=543156");
            }
            if (driver.getCurrentUrl().contains("jiangxi")) {
                urlTasks.add("http://jiangxi.ouchn.cn/mod/quiz/view.php?id=569320");
                urlTasks.add("http://jiangxi.ouchn.cn/mod/quiz/view.php?id=569321");
                urlTasks.add("http://jiangxi.ouchn.cn/mod/quiz/view.php?id=569322");
                urlTasks.add("http://jiangxi.ouchn.cn/mod/quiz/view.php?id=569323");
                urlTasks.add("http://jiangxi.ouchn.cn/mod/quiz/view.php?id=569324");
            }
        }


        //   Thread.sleep(20000000);


        for (String urlTask : urlTasks) {
            if (haveCompleteHomeWorkUrlSet.contains(urlTask)) {
                continue;
            }
            // FIXME 当完成第一份形考任务时，必须提交，否则会弹出 ”是否保存当前页面“消息
            driver.get(urlTask);
            // FIXME 延长了
            Thread.sleep(3 * 1000);
            // 点击继续作业

            boolean isGoOn = true;

            // cell c2
            CompleteInfo completeInfo = new CompleteInfo();
            try {
                List<WebElement> tdList = driver.findElements(By.cssSelector("td[class='cell c2']"));

                for (WebElement td : tdList) {
                    String score = td.getText();
                    //     System.err.println(score);
                    if ("还未评分".equals(score)) {
                        System.err.println("还未评分");
                        isGoOn = false;
                        break;
                    }
                }
                // feedback

                String scoreString = driver.findElement(By.id("feedback")).getText();
                String[] strs = scoreString.split("/");
                String s1 = strs[0].trim();
                s1 = s1.replaceAll("[^.^0-9]", "");
                String s2 = strs[1].trim();
                s2 = s2.replaceAll("[^.^0-9]", "");

                float s = Float.parseFloat(s1) / Float.parseFloat(s2);
                // if (s > 0.80) {
                // if (s > 0.70) {
             //   if (s > 0.90) {
                if (s > 0.99) {
        //        if (s > 0.75) {
                    completeInfo.setScore(s1);
                    System.err.println("成绩已达到，跳过");
                    isGoOn = false;
                }

            } catch (Exception e) {
                //    e.printStackTrace();
                //        Thread.sleep(2000);
            }

            if (!isGoOn) {
                boolean hasGoOn = false;
                for (WebElement we : driver.findElements(By.cssSelector("button[class='btn btn-secondary']"))) {
                    if (!Strings.isNullOrEmpty(we.getText()) && "继续上次试答".equals(we.getText().trim())) {
                        hasGoOn = true;
                    }
                }
                if (!hasGoOn) {
                    completeInfo.setComplete(true);
                    completeInfo.setHomeworkUrl(urlTask);
                    completeInfoList.add(completeInfo);
                    continue;
                }
            }

            try {
                Thread.sleep(5000);
                WebElement doWorkArea = driver.findElement(By.cssSelector("div[class='box py-3 quizattempt']"));
                doWorkArea.findElement(By.cssSelector("button[class='btn btn-secondary']")).click();
                Thread.sleep(2 * 1000);

                try {
                    //回到试题首页
                    WebElement element = driver.findElement(By.id("quiznavbutton1"));
                    element.click();
                    Thread.sleep(2 * 1000);
                } catch (Exception e) {

                }
                try {
                    driver.findElement(By.id("id_submitbutton")).click();
                    Thread.sleep(2 * 1000);
                } catch (Exception e) {

                }
            } catch (Exception e) {
                System.err.println("taskUrl:" + urlTask + "  occur error");
                e.printStackTrace();
                continue;
                //   closeDriver(driver);
                //   return;
            }


            // 回到首页
            Util.goHomePageIndex(driver);


            boolean hashNextPage = true;
            while (hashNextPage) {
                try {
                    Thread.sleep(4000);
                    // 单个页面的所有题目的集合
                    List<WebElement> singlePageQuestion = Util.getSinglePageQuestionList(driver);
                    // 遍历每个问题|题目


                    for (WebElement singleSubject : singlePageQuestion) {

                        WebElement contentElement = singleSubject.findElement(By.className("content"));

                        String title;
                        title = Util.getTitle(contentElement);
                        //兼容特殊字符
                        title = Util.dealContent(title);

                        String questionCode = MD5Utils.encode(subjectName + title);

                        // System.err.println("title:"+title);
                        AnswerObject answerObject = null;
                        if (answers.containsKey(questionCode)) {
                            answerObject = answers.get(questionCode);
                        } else if (originAnswers.containsKey(DealJsonString.saveZhWord(title))) {
                            answerObject = originAnswers.get(DealJsonString.saveZhWord(title));
                        }

                        if (answerObject == null) {
                            System.err.println("答案不存在:" + title);
                            // FIXME 如果问题不存在，就用HANLP来匹配
                            double similarity = 0.0;
                            String answerTitle = "";
                            for (Map.Entry<String, AnswerObject> entry : answerDTO.getOriginAnswers().entrySet()) {
                                double k1 = DealJsonString.getSimilarity(title, entry.getKey());
                                if (k1 > similarity) {
                                    similarity = k1;
                                    answerTitle = entry.getKey();
                                }
                            }
                            System.err.println("answerTitle:" + answerTitle + " similarity:" + similarity);
                            // 相似度为0.9 就选择
                            if (similarity > 0.30d) {
                                answerObject = answerDTO.getOriginAnswers().get(answerTitle);
                                System.err.println("???????:answerObject"+JSON.toJSONString(answerObject));
                            }
                        }
                      if(answerObject == null){
                            System.out.println("答案不存在111111111");
                            System.out.println(title);
                            Map<String, String> map = new HashMap<>();
                            map.put("答案不存在", "未能从题库中匹配到");
                            map.put("答案标题", title);
                            map.put("课程名", subjectName);
                            //  Thread.sleep(5000000);
                            continue;
                        }

                        WebElement answerElement = Util.findByClassName(contentElement, "answer");
                        if (null != answerElement) {
                            // 开始答题
                            Util.doExercise(driver, answerElement, answerObject.getQuestionType(), answerObject.getAnswers());
                        } else {
                            // 如果为空就是填空题 是没有答案对比的
                            // 10-23 加了一个文件上传
                            Util.doExercise(driver, singleSubject, answerObject.getQuestionType(), answerObject.getAnswers());
                        }
                        //休眠一秒
                        TimeUnit.SECONDS.sleep(1);
                        //  FIXME 此时答案是没有保存的，要点击结束试答题
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    Thread.sleep(2000);
                    // FIX ME 获取当前页面的下一页信息 设置为while还是有下一页就继续循环
                    WebElement nextPage = Util.findNextPage(driver);
                    if (nextPage != null) {
                        nextPage.click();
                    } else {
                        hashNextPage = false;
                        // FIXME  此时答案是没有保存的，要点击结束试答题 当没有下一页的时候，可以选择提交
                    }
                }
            }


            Thread.sleep(2000);


            WebElement submitbtns = driver.findElement(By.className("submitbtns"));
            WebElement next = submitbtns.findElement(By.cssSelector("input[name='next']"));
            next.click();
            Thread.sleep(2000);


            try {
                int sum = 0;
                int done = 0;
                for (WebElement tdWe : driver.findElements(By.cssSelector("td[class='cell c1 lastcol']"))) {
                    sum++;
                    if ("答案已保存".equals(tdWe.getText())) {
                        done++;
                    }
                }
               // if (done * 100 / sum < 90) {
                if (done * 100 / sum < 99) {
                    System.err.println("---------------------");
                    //Thread.sleep(20000000);
                    continue;
                }
            } catch (Exception e) {

            }


            if (!commit) {
                log.info("答案不提交");
                TimeUnit.SECONDS.sleep(2);
                continue;
            }

            //提交答案
            List<WebElement> saveButtons = driver.findElements(By.cssSelector("button[type='submit']"));
            //System.out.println("提交");
            //System.out.println(saveButtons.size());
            if (!CollectionUtils.isEmpty(saveButtons)) {
                for (WebElement webElement : saveButtons) {
                    String text = webElement.getText();
                    if (text.contains("提交")) {
                        webElement.click();
                    }
                }
            }

            TimeUnit.SECONDS.sleep(3);
            //全部提交
            //提交答案


            List<WebElement> confirmation = driver.findElements(By.className("confirmation-dialogue"));
            if (!CollectionUtils.isEmpty(confirmation)) {
                for (WebElement webElement : confirmation) {
                    List<WebElement> submitElement = webElement.findElements(By.tagName("input"));
                    if (!CollectionUtils.isEmpty(submitElement)) {
                        for (WebElement element1 : submitElement) {
                            String value = element1.getAttribute("value");
                            if (value.contains("提交")) {
                                //点击确认后页面会刷新,此时为了防止丢到元素抛异常，这里直接获取第一个，不再循环
                                element1.click();
                                break;
                            }

                        }
                    }
                }
            }


            List<WebElement> submitButtons = driver.findElements(By.tagName("input"));
            if (!CollectionUtils.isEmpty(submitButtons)) {
                for (WebElement webElement : submitButtons) {
                    String text = webElement.getText();
                    if (text.contains("提交")) {
                        webElement.click();
                    }
                }
            }

            TimeUnit.SECONDS.sleep(2);

            try {
                //判断是否符合要求
                Map<String, String> scoreMap = new HashMap<>();
                WebElement tbody = driver.findElement(By.tagName("tbody"));
                List<WebElement> trs = tbody.findElements(By.tagName("tr"));
                for (WebElement tr : trs) {
                    //th
                    WebElement th = tr.findElement(By.tagName("th"));
                    //td
                    WebElement td = tr.findElement(By.tagName("td"));
                    scoreMap.put(th.getText().trim(), td.getText().trim());
                }
                String score = scoreMap.get("分数");
                String[] strs = score.split("/");
                float s = Float.valueOf(strs[0]) / Float.valueOf(strs[1]);
                if (s < 0.80) {
                    scoreMap.put("科目", subjectName);
                    scoreMap.put("用户名", userName);
                    scoreMap.put("密码", password);
                    scoreMap.put("形考链接", urlTask);

                    if (push) {
                        HttpClientUtil.send(scoreMap);
                    }

                    System.out.println("答题不及格");
                    System.out.println(scoreMap.toString());
                } else {
                    completeInfo.setScore(score);
                    completeInfo.setComplete(true);
                    completeInfo.setHomeworkUrl(urlTask);
                    completeInfoList.add(completeInfo);
                }
            } catch (Exception e) {

            }

        }

        try {
            // 将新的完成作业的信息更新进去
            FileUtils.write(completeInfoFile, JSONObject.toJSONString(completeInfoList, SerializerFeature.PrettyFormat), "utf-8");

            Thread.sleep(5000);
        } catch (Exception e) {

        } finally {
            closeDriver(driver);
        }
    }

    private static void closeDriver(WebDriver driver) {
        try {
            driver.close();
            driver.quit();
        } catch (Exception e) {

        }
    }

    public static List<String> getQuizUrl(WebDriver driver, String userName) {
        Set<Cookie> cookies = driver.manage().getCookies();
        String token = "";
        for (Cookie c : cookies) {
            if ("MoodleSession".equals(c.getName())) {
                token = c.getValue();
            }
        }
        System.err.println("token:" + token);
//

        Document doc = SectionImport.getDocument(driver.getCurrentUrl(), userName, token);
        Elements courses = doc.getElementsByClass("course-content");
//System.out.println(courses.toString());

        if (CollectionsUtil.isEmpty(courses)) {
            System.out.println("为空");
            return Lists.newArrayList();
        }
        Element course = courses.get(0);
        int sectionCount = 200;
        List<String> lines = new ArrayList<>();
        for (int i = 2; i <= sectionCount; i++) {
            Element section = course.getElementById("section-" + i);
            //System.out.println(section.toString());
            if (null != section) {
                Elements instances = section.select("a[class=aalink]");
                for (Element instance : instances) {
                    //    System.err.println("instances::::::::::::::"+instance.text());
                    //  System.err.println("instances::::::::::::::11"+instance.ownText());
                    String href = instance.attr("href");
                    String instanceName = instance.getElementsByClass("instancename").get(0).ownText();
                    String line = String.format("%s,%s", href, instanceName);
                    System.out.println(line);
                    if (line.contains("quiz") && line.contains("作业")) {
                        lines.add(line);
                    }
                    if (line.contains("quiz") && line.contains("形考")) {
                        lines.add(line);
                    }
                }
                System.out.println("\n");
                System.out.println("\n");
                System.out.println("-----------------------------------------");
            }
        }
        return lines;

    }
}
